<?php
namespace wow\modelworld;

use \wow\model\dbcon as dbs;
use \wow\modelchar as charm;
/**
 * 
 * 
 * @Entity
 * @Table(name="playercreateinfo_item")
 * 
 */
class PlayerCreateItem{
	
	
	/**
     * @Id @Column(type="integer", name="race")
     */
	public $race;
	
	/**
     * @Id @Column(type="integer", name="class")
     */
	public $class;
	
	/**
	 * @Id @Column(type="integer", name="itemid")
	 */
	public $itemid;
	
	/**
	 * @Id @Column(type="integer", name="amount")
	 */
	public $amount;
	
	

	
	
	
	
	static public function parseItemsFromCode($code){
		
		$items = explode("\n", trim($code));
		$itemIdsAmount = array();
		
		foreach($items as $i){
			$exp = explode(':', trim($i));
			
			$id = intval($exp[0]);
			if ($id){
				$itemIdsAmount[$id] = isset($exp[1]) && (int)$exp[1] > 0 ? $exp[1] : 1;
			}
		}

		return $itemIdsAmount;
	}

	static public function parseItemsToCode($realmId, $class){
		$em = dbs\WorldDB::getEmFor($realmId);
		
		$races = charm\Character::getRacesForClass($class);
		
		
		
		$qb = $em->getWorldEM()->createQuery("SELECT i FROM wow\modelworld\PlayerCreateItem i WHERE i.class = ?1 AND i.race = ?2")
		->setParameter(1, $class)->setParameter(2, $races[0]);
		
		
		$results = $qb->getResult();
		
		$code = '';
		
		foreach($results as $res){
			$code .= $res->itemid . ":" . $res->amount . "\n";
		}
		
		
		return $code;
	}
	
	static public function updateItemsForClass($realmId, $class, $itemIdsAmount, $deleteOtherItemsThenItemids=false){
		$em = dbs\WorldDB::getEmFor($realmId);
		
		$races = charm\Character::getRacesForClass($class);
		
		
		$itemids = array_keys($itemIdsAmount);
		
		
		$qb = $em->getWorldEM()->createQuery("SELECT i FROM wow\modelworld\PlayerCreateItem i WHERE i.class = ?1")
		->setParameter(1, $class);
		$results = $qb->getResult();
		
		// Array of itemids that are already there!
		$dontadd = array();
		$delete = array();
		foreach($results as $res){
			if (!in_array($res->itemid, $itemids)){
				if ($deleteOtherItemsThenItemids){
					$delete[] = $res;
				}
			}else{
				$dontadd[] = $res->itemid;
			}
		}
		
		foreach($itemids as $itemid){
			if (!in_array($itemid, $dontadd)){
				foreach($races as $raceid){
					$p = new PlayerCreateItem();
					$p->race = $raceid;
					$p->class = $class;
					$p->itemid = $itemid;
					$p->amount = $itemIdsAmount[$itemid];
					
					$em->getWorldEM()->persist($p);
					
				}
				
			}
		}
		
		foreach($delete as $del){
			$em->getWorldEM()->createQuery("DELETE FROM wow\modelworld\PlayerCreateItem i WHERE i.class = ?1 AND i.itemid = ?2")
			->setParameter(1, $del->class)->setParameter(2, $del->itemid)->execute();
		}
		
		
		$em->getWorldEM()->flush();
		
	}
	
	
	
	
}
